#include "socket_client.h"

#include <unistd.h>
#include <cstdio>
#include <cstring>
#include <functional>

#include "logger.h"
#include "socket_data.h"

SocketClient::SocketClient(int clientFd)
    : clientFd_(clientFd)
{
    sem_init(&commandSem_, false, 0);
}

SocketClient::~SocketClient()
{
    running_ = false;
    sem_post(&commandSem_);
    thread_->join();
}

void SocketClient::RunTask(const std::string &message)
{
    LOGGER() << message << std::endl;
    currentCommand_ = message;
    sem_post(&commandSem_);
    if (thread_ == nullptr) {
        running_ = true;
        thread_ = std::make_unique<std::thread>(
            std::bind(&SocketClient::RunTaskMain, this));
    }
}

void SocketClient::RunTaskMain()
{
    while (running_) {
        sem_wait(&commandSem_);
        if (!running_) {
            break;
        }

        auto fp = popen(currentCommand_.c_str(), "r");

        struct SocketData data = {};
        data.size = fread(data.message, 1, sizeof(data.message), fp);
        fclose(fp);
        LOGGER() << data.size << " " << strerror(errno) << std::endl;
        write(clientFd_, &data, data.length());
    }
}
